package com.example.rocketmq.controller;

import com.example.rocketmq.service.MessageProducerService;
import com.example.rocketmq.service.RateLimitConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * RocketMQ限流消费测试控制器
 * 
 * @author demo
 */
@Slf4j
@RestController
@RequestMapping("/api/rocketmq")
public class RocketMQController {

    @Autowired
    private MessageProducerService producerService;

    @Autowired
    private RateLimitConsumerService consumerService;

    /**
     * 发送单条消息
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, String> request) {
        try {
            String content = request.get("content");
            if (content == null || content.trim().isEmpty()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "消息内容不能为空");
                return ResponseEntity.badRequest().body(errorMap);
            }

            // 这里简化处理，实际应该创建Message对象
            log.info("收到发送消息请求: {}", content);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "消息发送请求已接收");
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送消息失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

    /**
     * 批量发送消息
     */
    @PostMapping("/send-batch")
    public ResponseEntity<Map<String, Object>> sendBatchMessages(@RequestBody Map<String, Object> request) {
        try {
            Integer count = (Integer) request.get("count");
            if (count == null || count <= 0) {
                count = 1000; // 默认发送1000条
            }

            log.info("开始批量发送 {} 条消息", count);
            
            // 异步发送，避免阻塞HTTP请求
            final int finalCount = count;
            new Thread(() -> {
                try {
                    producerService.sendBatchMessages(finalCount);
                } catch (Exception e) {
                    log.error("批量发送消息失败", e);
                }
            }).start();

            Map<String, Object> response = new HashMap<>();
            response.put("message", "批量发送消息任务已启动");
            response.put("count", count);
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("批量发送消息失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

    /**
     * 获取消费统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getConsumptionStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            stats.put("consumedThisMinute", consumerService.getConsumedThisMinute());
            stats.put("totalConsumed", consumerService.getTotalConsumed());
            stats.put("rateLimitEnabled", consumerService.isRateLimitEnabled());
            stats.put("rateLimitPerMinute", 10); // 从配置中获取
            stats.put("timestamp", System.currentTimeMillis());
            stats.put("statsDescription", consumerService.getConsumptionStats());
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取消费统计信息失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

    /**
     * 启用/禁用限流
     */
    @PostMapping("/rate-limit")
    public ResponseEntity<Map<String, Object>> toggleRateLimit(@RequestBody Map<String, Boolean> request) {
        try {
            Boolean enabled = request.get("enabled");
            if (enabled == null) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "enabled参数不能为空");
                return ResponseEntity.badRequest().body(errorMap);
            }

            consumerService.setRateLimitEnabled(enabled);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "限流功能已" + (enabled ? "启用" : "禁用"));
            response.put("rateLimitEnabled", consumerService.isRateLimitEnabled());
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("切换限流状态失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "RocketMQ Rate Limit Demo");
        health.put("timestamp", System.currentTimeMillis());
        health.put("version", "1.0.0");
        
        return ResponseEntity.ok(health);
    }

    /**
     * 获取系统信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getSystemInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("javaVersion", System.getProperty("java.version"));
        info.put("javaHome", System.getProperty("java.home"));
        info.put("osName", System.getProperty("os.name"));
        info.put("osVersion", System.getProperty("os.version"));
        info.put("userHome", System.getProperty("user.home"));
        info.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(info);
    }
}
